import React from 'react';
import cl from 'classnames';
import { Select, Input, InputNumber, Checkbox } from 'antd';
import { cloneDeep } from 'lodash';
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import { FieldNodeSchema } from '@/app/codeTreeSlice';
import IconFont from '@/components/Iconfont';
import FloorTitleMore from '../fields/FloorTitleMore';
import singleBg from '@/assets/images/ic_bg_assembly.svg';
import moreIcon from '@/assets/images/icon_arrow_right_m.svg';
import IMessage from '@/utils/IMessage';
import styles from '../index.less';
import style from './index.less';

const ALL_BALANCE_TYPES = [
  { type: 'Voice', defaultLabel: 'Voice' },
  { type: 'SMS', defaultLabel: 'SMS' },
  { type: 'Data', defaultLabel: 'Data' },
  { type: 'Currency', defaultLabel: 'Currency' },
];

export default function renderUsageTrendsProd2(
  focusComponent: FieldNodeSchema | undefined,
  handleChange: (value: any, key: string) => void,
) {
  const topMarginStyle = { marginTop: '16px' };
  const enabledTypes = focusComponent?.props?.enabledBalanceTypes || ['Voice', 'SMS', 'Data'];
  const labels = focusComponent?.props?.balanceTypeLabels || {};

  // 构建类似 UsageTrendsProd 的 balanceTypeList 结构用于显示
  const balanceTypeList = ALL_BALANCE_TYPES.map((item) => ({
    type: item.type,
    visible: enabledTypes.includes(item.type),
    label: labels[item.type] || item.defaultLabel,
  }));

  // 向下交换
  const onDown = (index: number) => {
    if (index + 1 !== balanceTypeList.length) {
      const newList = [...balanceTypeList];
      [newList[index], newList[index + 1]] = [newList[index + 1], newList[index]];
      updateFromList(newList);
    }
  };

  // 向上交换
  const onUp = (index: number) => {
    if (index !== 0) {
      const newList = [...balanceTypeList];
      [newList[index], newList[index - 1]] = [newList[index - 1], newList[index]];
      updateFromList(newList);
    }
  };

  // 从 list 更新到 enabledBalanceTypes 和 balanceTypeLabels
  const updateFromList = (list: any[]) => {
    const newEnabled = list.filter((i) => i.visible).map((i) => i.type);
    const newLabels = {};
    list.forEach((i) => {
      if (i.label !== ALL_BALANCE_TYPES.find((t) => t.type === i.type)?.defaultLabel) {
        newLabels[i.type] = i.label;
      }
    });
    handleChange(newEnabled, 'enabledBalanceTypes');
    handleChange(newLabels, 'balanceTypeLabels');
  };

  const handleToChange = (value: any, key: string, index: number) => {
    if (key === 'visible' && !value) {
      const visibleCount = balanceTypeList.filter((i) => i.visible).length;
      if (visibleCount === 1) {
        IMessage.warning('Please display at least one Balance Type.');
        return;
      }
    }
    const newList = cloneDeep(balanceTypeList);
    newList[index][key] = value;
    updateFromList(newList);
  };

  return (
    <div className={style.subsWrap}>
      <FloorTitleMore
        showTitle={focusComponent?.props.showTitleBar}
        title={focusComponent?.props.title}
        showMore={focusComponent?.props.showMore}
        moreName={focusComponent?.props.moreText}
        moreLink={focusComponent?.props.jumpLink}
        showMoreIcon
        moreIcon={
          focusComponent?.props.moreIcon || [
            {
              src: moreIcon,
              width: 0,
              height: 0,
            },
          ]
        }
        titleIcon={
          focusComponent?.props.titleIcon || [
            {
              src: singleBg,
              width: 0,
              height: 0,
            },
          ]
        }
        type={focusComponent?.type}
        onTitleIconChange={(value, key) => {
          handleChange(value, key || 'titleIcon');
        }}
        onTitleVisibleChange={(checked: boolean) => {
          handleChange(checked, 'showTitleBar');
          handleChange(checked, 'showMore');
        }}
        onTitleChange={(value: string) => {
          handleChange(value, 'title');
        }}
        onMoreVisibleChange={(checked: boolean) => {
          handleChange(checked, 'showMore');
        }}
        onMoreNameChange={(value: string) => {
          handleChange(value, 'moreText');
        }}
        onMoreLinkChange={(value: string) => {
          handleChange(value, 'jumpLink');
        }}
      />

      <div className={styles.myTitle} style={topMarginStyle}>
        Balance Type
      </div>
      <div className={cl(style.uploadImgBox)}>
        {balanceTypeList.map((item: any, index: number) => {
          return (
            <div key={item.type} style={{ marginBottom: '12px' }}>
              <div className={cl(style.imgItemWrap)}>
                <div className={style.controlBox}>
                  <div>
                    <IconFont
                      type="icon-ic_upper1"
                      className={cl(style.icon, index === 0 && style.disabledIcon)}
                      onClick={() => onUp?.(index)}
                    />
                  </div>
                  <div>
                    <IconFont
                      type="icon-ic_upperbeifen"
                      className={cl(style.icon, index === balanceTypeList.length - 1 && style.disabledIcon)}
                      onClick={() => onDown?.(index)}
                    />
                  </div>
                </div>
                <div className={style.imgItem}>
                  <div className={style.titleBox}>
                    <span>{item.label}</span>
                    <div>
                      {item.visible ? (
                        <EyeOutlined
                          className={style.eyeIcon}
                          onClick={() => handleToChange(false, 'visible', index)}
                        />
                      ) : (
                        <EyeInvisibleOutlined
                          className={style.eyeIcon}
                          onClick={() => handleToChange(true, 'visible', index)}
                        />
                      )}
                    </div>
                  </div>
                  <div className="mt1" style={{ width: '100%' }}>
                    <Input
                      placeholder="Please enter"
                      value={item.label}
                      showCount
                      maxLength={20}
                      onChange={(e) => handleToChange(e.target.value, 'label', index)}
                    />
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className={styles.myTitle} style={topMarginStyle}>
        Default Active Tab
      </div>
      <Select
        value={focusComponent?.props?.defaultActiveTab}
        onChange={(value) => {
          handleChange(value, 'defaultActiveTab');
        }}
        placeholder="Please select"
        style={{ width: '100%' }}
        options={enabledTypes.map((type) => ({
          label: labels[type] || type,
          value: type,
        }))}
      />

      <div className={styles.myTitle} style={topMarginStyle}>
        Max Tab Count
      </div>
      <InputNumber
        value={focusComponent?.props?.maxTabCount || 4}
        onChange={(value) => {
          handleChange(value, 'maxTabCount');
        }}
        min={1}
        max={4}
        style={{ width: '100%' }}
      />

      <div className={styles.myTitle} style={topMarginStyle}>
        Display Months
      </div>
      <Select
        value={focusComponent?.props?.displayMonths}
        onChange={(value) => {
          handleChange(value, 'displayMonths');
        }}
        placeholder="Please select"
        style={{ width: '100%' }}
        options={[
          { label: '3 Months', value: 3 },
          { label: '6 Months', value: 6 },
          { label: '12 Months', value: 12 },
        ]}
      />

      <div className={styles.myTitle} style={topMarginStyle}>
        Subtitle Text
      </div>
      <Input
        value={focusComponent?.props?.subtitleText}
        onChange={(e) => {
          handleChange(e.target.value, 'subtitleText');
        }}
        placeholder="Please enter subtitle"
        showCount
        maxLength={50}
        style={{ width: '100%' }}
      />
    </div>
  );
}
